/*
 *   Copyright 2021 zzh
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

package com.aduib.boot.common.concurrent;

import java.util.Objects;
import java.util.concurrent.ThreadFactory;

/**
 * @author ZZH
 * @version 1.0.0 线程工厂创建类
 */
public class ThreadFactoryBuilder {

  /**
   * @param threadName
   * @return
   */
  public static ThreadFactory createJava(String threadName) {
    return new DefaultThreadFactory(threadName);
  }

  public static ThreadFactory createJava(String threadName, boolean daemon) {
    return new DefaultThreadFactory(threadName,daemon);
  }

  public static ThreadFactory createJava(String threadName, int priority, boolean daemon) {
    return new DefaultThreadFactory(threadName,priority,daemon);
  }

  /**
   * @param threadName
   * @param priority
   * @param daemon
   * @return
   */
  public static ThreadFactory createGuava(String threadName, int priority, boolean daemon) {
    return new com.google.common.util.concurrent.ThreadFactoryBuilder()
        .setNameFormat(threadName)
        .setPriority(priority)
        .setDaemon(daemon)
        .setThreadFactory(createJava(threadName))
        .build();
  }

  /**
   * @param threadName
   * @param priority
   * @param daemon
   * @param
   * @return
   */
  public static ThreadFactory createGuava(
      String threadName,
      int priority,
      boolean daemon,
      Thread.UncaughtExceptionHandler uncaughtExceptionHandler) {
    if (Objects.isNull(uncaughtExceptionHandler)) {
      createGuava(threadName, priority, daemon);
    }
    return new com.google.common.util.concurrent.ThreadFactoryBuilder()
        .setNameFormat(threadName)
        .setPriority(priority)
        .setDaemon(daemon)
        .setThreadFactory(createJava(threadName))
        .setUncaughtExceptionHandler(uncaughtExceptionHandler)
        .build();
  }
}
